using System;
using System.Collections;
using System.Threading;
using System.Web;

namespace CodeStory.Core.Authentication
{
	/// <summary>
	/// Enables ASP.NET applications to use Custom authentication based on forms authentication. 
	/// This class cannot be inherited.
	/// </summary>
	public sealed class CustomAuthenticationModule : IHttpModule
	{
		private const string CodeStoryAuthenticationCookieName = "_CodeStoryAuth_";

		//private const string AUTHENTICATION_COOKIE_KEY = "CustomAuthentication.Cookie.Name";

		/// <summary>
		/// Initializes the module derived from IHttpModule when called by the HttpRuntime . 
		/// </summary>
		/// <param name="app">The HttpApplication module</param>
		public void Init(HttpApplication app) {
			app.AuthenticateRequest += new EventHandler(this.OnAuthenticate);
		}

		private void OnAuthenticate(object sender, EventArgs e) {
			HttpApplication app = (HttpApplication)sender;
			HttpRequest req = app.Request;
			HttpResponse res = app.Response;

			string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl;
			if (loginUrl == null || loginUrl.Trim() == String.Empty) {
				//throw new Exception(" CustomAuthentication.LoginUrl entry not found in appSettings section of Web.config");
				loginUrl = "~/CodeStory_Core_Login.portlet.aspx";
			}

			int i = req.Path.LastIndexOf("/");
			string page = req.Path.Substring(i + 1, (req.Path.Length - (i + 1)));

			int j = loginUrl.LastIndexOf("/");
			string loginPage = loginUrl.Substring(j + 1, (loginUrl.Length - (j + 1)));

			if (page != null && !(page.Trim().ToUpper().Equals(loginPage.ToUpper()))) {
				if (req.Cookies.Count > 0 && req.Cookies[CodeStoryAuthenticationCookieName.ToUpper()] != null) {
					HttpCookie cookie = req.Cookies[CodeStoryAuthenticationCookieName.ToUpper()];
					if (cookie != null) {
						string str = cookie.Value;
						CustomIdentity userIdentity = CustomAuthentication.Decrypt(str);
						string[] roles = userIdentity.UserRoles.Split(new char[] {'|'});
						ArrayList arrRoles = new ArrayList();
						arrRoles.InsertRange(0, roles);
						CustomPrincipal principal = new CustomPrincipal(userIdentity, arrRoles);
						app.Context.User = principal;
						Thread.CurrentPrincipal = principal;
					}
				} else {
					res.Redirect(req.ApplicationPath + loginUrl + "?ReturnUrl=" + req.Path, true);
				}
			}
		}

		public void Dispose() {
		}
	}

	public static class CustomAuthentication
	{
		public static CustomIdentity Decrypt(string val) {
			throw new NotImplementedException();
		}
	}
}